# 实现一个timeit的装饰器：timeit 装饰能够计算被装饰函数的运行时间

from functools import wraps
from datetime import datetime
import inspect
from pathlib import Path

import time


def timeit(fn):
    """
    将被装饰的函数名，执行的开始时间，结束时间以的方式保存起来
    :param fn: 被装饰的函数
    :return:
    """

    @wraps(fn)
    def _timeit(*args, **kwargs):
        start = datetime.now()
        result = fn(*args, **kwargs)
        end = datetime.now()
        # print("The function start is {:%H:%M:%S}, end is {:%H:%M:%S}, delta is {:.2f}s".format(start, end, delta))

        return result, start, end

    return _timeit


def log_it(fn):
    @wraps(fn)
    def _log_it(*args, **kwargs):
        result = fn(*args, **kwargs)

        log_path = Path('./logs')
        log_path.mkdir(parents=True, exist_ok=True)
        file_name = Path(f'./logs/{datetime.now():%Y%m%d}.log')
        file_name.touch(exist_ok=True)
        with file_name.open('a') as f:
            f.write("The function  start time is {:%H:%M:%S},end time is {:%H:%M：%S},delta is {:.2f}s.\n".format(
                result[1], result[2], (result[1] - result[2]).total_seconds()))

        return result

    return _log_it


@log_it
@timeit
def add(x, y):
    time.sleep(3.778)
    return x + y


print(add(y=50, x=60))
